package com.by.controller;

import com.by.bean.ResultBean;
import com.by.service.MinioService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/minio")
@Api(tags =  "minio文件服务")
public class MinioController extends BaseController {

    @Autowired
    private MinioService minioService;

    /**
     * 上传文件
     * @param file
     * @return
     */
    @ApiOperation(value = "上传文件")
    @PostMapping("/upload")
    public ResultBean uploadFile(@RequestParam("file") MultipartFile file) {
        String url = minioService.uploadFile(file);
        return success("上传成功", url);
    }

    /**
     * 批量上传文件
     * @param files
     * @return
     */
    @PostMapping("/upload/batch")
    @ApiOperation(value = "批量上传文件")
    public ResultBean uploadFiles(@RequestParam("files") List<MultipartFile> files) {
        List<String> urls = minioService.uploadFiles(files);
        return success("上传成功", urls);
    }

    /**
     * 获取文件URL
     * @param fileName
     * @return
     */
    @GetMapping("/url/{fileName}")
    @ApiOperation(value = "获取文件URL")
    public ResultBean getFileUrl(@PathVariable String fileName) {
        String url = minioService.getFileUrl(fileName);
        return success("获取成功", url);
    }

    /**
     * 删除文件
     * @param fileName
     * @return
     */
    @DeleteMapping("/{fileName}")
    @ApiOperation(value = "删除文件")
    public ResultBean deleteFile(@PathVariable String fileName) {
        minioService.deleteFile(fileName);
        return success("删除成功");
    }

    /**
     * 下载文件
     * @param fileName
     * @param response
     */
    @GetMapping("/download/{fileName}")
    @ApiOperation(value = "下载文件")
    public void downloadFile(@PathVariable String fileName, HttpServletResponse response) {
        try {
            InputStream inputStream = minioService.downloadFile(fileName);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                response.getOutputStream().write(buffer, 0, bytesRead);
            }
            inputStream.close();
        } catch (Exception e) {
            log.error("下载文件失败", e);
            throw new RuntimeException("下载文件失败", e);
        }
    }
} 